package com.thinvent.foxit.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thinvent.foxit.dto.ApplyUserKeyResponse;
import com.thinvent.foxit.entity.UserAuthLog;
import com.thinvent.foxit.mapper.UserAuthLogMapper;
import com.thinvent.foxit.mapper.UserAuthMapper;
import com.thinvent.foxit.entity.UserAuth;
import com.thinvent.foxit.service.UserAuthService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (UserAuth)表服务实现类
 *
 * @author makejava
 * @since 2024-07-17 14:42:22
 */
@Service("userAuthService")
public class UserAuthServiceImpl extends ServiceImpl<UserAuthMapper, UserAuth> implements UserAuthService {

    @Resource
    private UserAuthMapper userAuthMapper;

    @Resource
    private UserAuthLogMapper userAuthLogMapper;

    @Override
    public void flush() {
        // 获取本地文件
        String filePath = "D:\\访问密钥(剩余).txt";
        List<String[]> lines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 使用逗号作为分隔符分割每一行
                String[] values = line.split(",");
                lines.add(values);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }

        // 打印读取到的数据
        for (String[] row : lines) {
            for (String value : row) {
                try {
                    // 构建用户秘钥对象并插入数据库
                    UserAuth userAuth = new UserAuth();
                    userAuth.setAuthStr(value);
                    Date utilDate = new Date();
                    Timestamp timestampFromDate = new Timestamp(utilDate.getTime());
                    userAuth.setCreateTime(timestampFromDate);
                    userAuth.setUpdateTime(timestampFromDate);
                    userAuthMapper.insert(userAuth);
                } catch (Throwable throwable) {

                }
            }
        }
    }

    @Override
    public Integer applyUserKey(String id, String clientIp) {
        // 创建UpdateWrapper实例，用于构造更新条件
        UpdateWrapper<UserAuth> updateWrapper = new UpdateWrapper<>();
        // 设置更新条件，例如根据id更新
        updateWrapper.eq("id", id);

        UserAuth userAuth = new UserAuth();
        userAuth.setOccupyStartTime(new Date());
        userAuth.setRemoteIp(clientIp);
        int update = userAuthMapper.update(userAuth, updateWrapper);
        return update;
    }

    @Override
    public Integer unApplyUserKey(String id) {
        UserAuth userAuth = new UserAuth();
        userAuth.setId(id);
        userAuth.setOccupyStartTime(null);
        userAuth.setRemoteIp(null);
        int update = userAuthMapper.updateById(userAuth);
        return update;
    }

    @Override
    public Integer applyUserKeyRandom(String clientIP) {
        // 一个ip只能申请一次秘钥
        QueryWrapper<UserAuthLog> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("remote_ip", clientIP);

        // 如果存在ip记录 则无法申请
        List<UserAuthLog> userAuthLogs = userAuthLogMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(userAuthLogs)) {
            return 0;
        }

        // 获取随机的一个秘钥 并申请到该用户的ip
        QueryWrapper<UserAuth> wrapper = new QueryWrapper<>();

        wrapper.orderBy(true, true, "RAND()");

        wrapper.last("LIMIT 1");

        List<UserAuth> userAuths = userAuthMapper.selectList(wrapper);

        if (!userAuths.isEmpty()) {
            UserAuth userAuth = userAuths.get(0);
            UserAuthLog userAuthLog = new UserAuthLog();
            userAuthLog.setAuthId(userAuth.getId());
            userAuthLog.setRemoteIp(clientIP);
            Date utilDate = new Date();
            Timestamp timestampFromDate = new Timestamp(utilDate.getTime());
            userAuthLog.setCreateTime(timestampFromDate);
            userAuthLog.setUpdateTime(timestampFromDate);
            return userAuthLogMapper.insert(userAuthLog);
        } else {
            return 0;
        }
    }

    @Override
    public ApplyUserKeyResponse applyUserKeyDetail(String clientIP) {
        QueryWrapper<UserAuthLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("remote_ip", clientIP);
        List<UserAuthLog> userAuthLogs = userAuthLogMapper.selectList(queryWrapper);
        if(!userAuthLogs.isEmpty()) {
            UserAuthLog userAuthLog = userAuthLogs.get(0);
            String authId = userAuthLog.getAuthId();
            UserAuth userAuth = userAuthMapper.selectById(authId);
            ApplyUserKeyResponse applyUserKeyResponse = new ApplyUserKeyResponse();
            applyUserKeyResponse.setAuthStr(userAuth.getAuthStr());
            applyUserKeyResponse.setRemoteIP(clientIP);
            applyUserKeyResponse.setNextChatUrl("http://192.168.110.93/#/chat");
            return applyUserKeyResponse;
        }
        return new ApplyUserKeyResponse();
    }
}

